package com.mmall.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class CookieUtil {

    //todo 上线此值需要修改
    private final  static String COOKIE_DOMAIN =".happymmall.com";
    private final static String COOKIE_NAME = "mmall_login_token";


    public static String readLoginToken(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie ck : cookies){
                log.info("read cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
                if (StringUtils.equals(ck.getName(),COOKIE_NAME)){
                    log.info("return cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
                    return ck.getValue();
                }
            }
        }
        return null;
    }


    //a: A.happlymmall.com                  cookie:domain=A.happymmall.com; path="/"
    //b: B.happlymmall.com                  cookie:domain=b.happymmall.com; path="/"
    //c: A.happlymmall.com/test/cc          cookie:domain=A.happymmall.com; path="/test/cc"
    //a: A.happlymmall.com/test/dd          cookie:domain=A.happymmall.com; path="/test/dd"
    //e: A.happlymmall.com/test/            cookie:domain=A.happymmall.com; path="/test/dd"
    //X:domain=".happymmall.com"
    public  static  void  writeLoginToken(HttpServletResponse response,String token){
        Cookie cookies = new Cookie(COOKIE_NAME,token);
       // cookies.setDomain(COOKIE_DOMAIN);
        cookies.setPath("/"); //代表设置在根目录
        cookies.setHttpOnly(true);
        //单位是秒
        //如果着个maxaget 不设置的话 cookie 就不会写入硬盘，而是写在内存，只在当前页面有用。
        cookies.setMaxAge(60*60*24*365); //如果是-1 代表永久
        log.info("write cookieName:{},cookieValue:{}",cookies.getName(),cookies.getValue());
        response.addCookie(cookies);

    }


    public static void delLoginToken(HttpServletResponse response,HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie ck : cookies){
                if (StringUtils.equals(ck.getName(),COOKIE_NAME)){
                    ck.setDomain(COOKIE_DOMAIN);
                    ck.setPath("/");
                    ck.setMaxAge(0); //设置成0，代表删除此cookie.
                    log.info("del cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
                    response.addCookie(ck);
                    return;
                }
            }
        }
    }

}
